<script setup lang="ts">
import { toRef, ref, createVNode } from "vue";
import { Handle, useNodeConnections } from "@vue-flow/core";
import { useRouter } from 'vue-router'
import {
  addDialog,
  closeDialog,
  closeAllDialog
} from "@/components/ReDialog";
import { h, VNode, computed } from 'vue';
import { ElButton } from 'element-plus';

const router = useRouter()

function goToDetail(id) {
  router.push(`/device-detail/${id}`)
}
const props = defineProps({
  data: {
    type: Object,
    required: true
  },
  sourcePosition: {
    type: String
  },
  targetPosition: {
    type: String
  },

});

const sourceConnections = useNodeConnections({
  handleType: "target"
});

const targetConnections = useNodeConnections({
  handleType: "source"
});

const isSender = toRef(() => sourceConnections.value.length <= 0);

const isReceiver = toRef(() => targetConnections.value.length <= 0);

const bgColor = toRef(() => {
  // if (isSender.value) {
  //   return "#2563eb";
  // }

  if (props.data.hasError) {
    return "#f87171";
  }

  if (props.data.isFinished) {
    // return "#334155";
    return "transparent";
  }

  if (props.data.isCancelled) {
    return "#fbbf24";
  }

  // return "#4b5563";
  return "transparent";
});

const labelToImageMap = {
  "设备1": new URL('@/assets/screen/service1.png', import.meta.url).href,
  "设备2": new URL('@/assets/screen/service1.png', import.meta.url).href,
  "设备3": new URL('@/assets/screen/service1.png', import.meta.url).href,
  "设备4": new URL('@/assets/screen/service1.png', import.meta.url).href,
  "设备5": new URL('@/assets/screen/service1.png', import.meta.url).href,
  "设备6": new URL('@/assets/screen/service1.png', import.meta.url).href,
  "设备7": new URL('@/assets/screen/service1.png', import.meta.url).href,
  "设备8": new URL('@/assets/screen/service1.png', import.meta.url).href,
  "设备9": new URL('@/assets/screen/service1.png', import.meta.url).href,
  "设备10": new URL('@/assets/screen/service1.png', import.meta.url).href,
  "设备11": new URL('@/assets/screen/service1.png', import.meta.url).href,
  "设备12": new URL('@/assets/screen/service1.png', import.meta.url).href,
  "设备13": new URL('@/assets/screen/service1.png', import.meta.url).href,
  "设备14": new URL('@/assets/screen/service1.png', import.meta.url).href,
  "设备15": new URL('@/assets/screen/service1.png', import.meta.url).href,
  "设备16": new URL('@/assets/screen/service1.png', import.meta.url).href,
  "设备17": new URL('@/assets/screen/service1.png', import.meta.url).href,
  "设备18": new URL('@/assets/screen/service1.png', import.meta.url).href,
  "设备19": new URL('@/assets/screen/service1.png', import.meta.url).href,
  "设备20": new URL('@/assets/screen/service1.png', import.meta.url).href,
  "设备21": new URL('@/assets/screen/service1.png', import.meta.url).href,
  "设备22": new URL('@/assets/screen/service1.png', import.meta.url).href,
  "设备23": new URL('@/assets/screen/service1.png', import.meta.url).href,
  "设备24": new URL('@/assets/screen/service1.png', import.meta.url).href,
  "设备25": new URL('@/assets/screen/service1.png', import.meta.url).href,
  "设备26": new URL('@/assets/screen/service1.png', import.meta.url).href,
  "设备27": new URL('@/assets/screen/service1.png', import.meta.url).href,
  "设备28": new URL('@/assets/screen/service1.png', import.meta.url).href,
  "设备29": new URL('@/assets/screen/service1.png', import.meta.url).href,
  "设备30": new URL('@/assets/screen/service1.png', import.meta.url).href,

};
const processLabel = toRef(() => {
  if (props.data.hasError) {
    return "❌";
  }

  if (props.data.isSkipped) {
    return "🚧";
  }

  if (props.data.isCancelled) {
    return "🚫";
  }

  // if (isSender.value) {
  //   return "📦";
  // }

  if (props.data.isFinished) {
    return props.data.label?.toString();
  }
  // return "🔋";
  // 正常情况，返回label；如果没有label，显示"未知设备"
  // return props.data.label?.toString() || "未知设备";
  return labelToImageMap[props.data.label?.toString()] || labelToImageMap["未知设备"];

});


const dialogVisible = ref(false);
function onPopConfirmClose() {
  // 可以加业务逻辑或提示关闭
}
function goToNodeDetail(id: string) {
  dialogVisible.value = true;
}


const nodeDetailMap: Record<string, () => VNode> = {
  "设备1": () =>
    createVNode('div', {
      style: `
        position: fixed;
        top: 0;
        left: 0;
        height: 100vh;
        width: 100vw;
        margin: 0;
        padding: 0;
        display: flex;
        justify-content: center;
        align-items: center;
        background-color: #0b1d3a;
        font-family: 'Segoe UI', sans-serif;
        overflow: auto;
      `
    }, [
      createVNode('div', {
        style: `
          display: flex;
          justify-content: space-between;
          align-items: flex-start;
          gap: 40px;
          padding: 30px 40px;
          width: 90vw;
          max-width: 1500px;
          height: auto;
          background-color: #12284c;
          border-radius: 16px;
          box-shadow: 0 0 30px rgba(0, 0, 0, 0.5);
          color: #f0f0f0;
        `
      }, [

        // 左栏 - 描述
        createVNode('div', {
          style: 'flex: 1; text-align: right; font-size: 20px; line-height: 1.8;'
        }, [
          createVNode('h3', { style: 'color: #4fc3f7; margin-bottom: 12px;' }, '功能简介'),
          createVNode('ul', { style: 'list-style-position: inside;' }, [
            createVNode('li', null, '支持多规格注液'),
            createVNode('li', null, '自动补液 + 校准'),
            createVNode('li', null, '高精度流量控制'),
            createVNode('li', null, '设备稳定性高，24小时运行')
          ])
        ]),

        // 中间图片
        createVNode('div', {
          style: `
            flex: 0 0 600px;
            text-align: center;
          `
        }, [
          createVNode('img', {
            src: 'https://tse4.mm.bing.net/th?id=OIP.IgEJDa2rflmQEAPuxa1x0AHaE-&pid=Api',
            style: `
              width: 100%;
              border-radius: 12px;
              box-shadow: 0 6px 20px rgba(0, 0, 0, 0.4);
              margin-bottom: 10px;
            `
          }),
          createVNode('p', {
            style: 'font-size: 15px; color: #ccc;'
          }, '电芯注液机 - 型号 EX-800')
        ]),

        // 右栏 - 参数
        createVNode('div', {
          style: 'flex: 1; font-size: 20px; line-height: 1.8;'
        }, [
          createVNode('h3', { style: 'color: #4fc3f7; margin-bottom: 12px;' }, '技术参数'),
          createVNode('table', {
            style: 'width: 100%; border-collapse: collapse; font-size: 14px;'
          }, [
            ['型号', 'EX-800'],
            ['运行状态', '运行中 ✅'],
            ['工位编号', '注液工位 1'],
            ['注液速度', '45 电芯 / 分钟'],
            ['注液精度', '±0.05ml']
          ].map(([k, v]) =>
            createVNode('tr', null, [
              createVNode('td', {
                style: 'padding: 8px 12px; font-weight: bold; color: #ccc; width: 120px;'
              }, k),
              createVNode('td', {
                style: 'padding: 8px 12px;'
              }, v)
            ])
          ))
        ])
      ])
    ])
};


function onFullscreenClick(label: string) {
  addDialog({
    fullscreen: true,
    showClose: false,
    hideFooter: true,
    hideHeader: false,
    modal: true,
    style: 'padding: 0; background-color: #0b1d3a;', // ✅ 消除默认白边和背景色

    // ✅ 自定义 header 右上角关闭按钮
    headerRenderer: (): VNode => {
      return h('div', {
        style: `
          position: relative;
          width: 100%;
          height: 0;
        `
      }, [
        h('button', {
          style: `
            position: absolute;
            top: 0px;
            right: 5px;
            font-size: 24px;
            background: none;
            border: none;
            color: white;
            cursor: pointer;
            z-index: 1000;
            transition: color 0.2s;
          `,
          onMouseenter: (e) => ((e.currentTarget as HTMLElement).style.color = '#ff4d4f'),
          onMouseleave: (e) => ((e.currentTarget as HTMLElement).style.color = '#ffffff'),
          onClick: () => closeAllDialog()
        }, '✖')
      ]);
    },

    // ✅ 内容区域渲染
    contentRenderer: () => {
      const content =
        nodeDetailMap[label]?.() ||
        createVNode('div', {
          style: `
            flex: 1;
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 24px;
            color: white;
          `
        }, [`${label} 的详情暂未配置`]);

      // ✅ 外壳始终撑满全屏
      return createVNode('div', {
        style: `
          height: 100vh;
          width: 100vw;
          display: flex;
          flex-direction: column;
          background-color: #0b1d3a;
          overflow: auto;
        `
      }, [content]);
    }
  });
}

const getLabelImage = () => {
  const label = props.data.label?.toString() || "未知设备";
  return labelToImageMap[label] || labelToImageMap["未知设备"];
};
const getButtonClass = () => {
  return props.data.isRunning ? 'btn-green' : 'btn-red'
}
const handleClick = (label: string, value: any) => {
  popoverVisible.value?.hide?.()
  alert(`${label}：${value || '无数据'}`)
}
const popoverVisible = ref()
</script>

<template>
  <div>
    <el-popover placement="top-start" width="260" trigger="click" :teleported="true" v-model:visible="popoverVisible">
      <!-- 插槽内容：显示设备信息 -->
      <template #default>
        <div class="popconfirm-content">
          <p><strong>设备型号:</strong> {{ data.deviceModel || '未知型号' }}</p>
          <p><strong>设备状态:</strong> {{ data.deviceStatus || '未知状态' }}</p>
          <p><strong>设备标签:</strong> {{ data.deviceLabel || '无标签' }}</p>
          <!-- 文字跳转链接 -->
          <p @click="onFullscreenClick(data.label)"
            style="color: #409EFF; cursor: pointer; text-decoration: underline; margin-top: 10px;">
            查看详情
          </p>

        </div>
      </template>

      <!-- reference 插槽：流程节点触发区域 -->
      <template #reference>
        <div class="process-node" :style="{
      backgroundColor: bgColor,
      boxShadow: data.isRunning ? '0 0 10px rgba(0, 0, 0, 0.5)' : ''
    }">
          <Handle v-if="!isSender" type="target" :position="targetPosition as any">

          </Handle>
          <Handle v-if="!isReceiver" type="source" :position="sourcePosition as any" />
          <div v-if="!isSender && data.isRunning" class="spinner" />
          <!-- 始终显示的设备图 + 按钮 -->
          <div
            :style="{ backgroundImage: `url(${getLabelImage()})`, backgroundSize: 'cover', width: '100%', height: '100%', justifyContent: 'center', alignItems: 'center', display: 'flex' }">
            <!-- 用 el-row 实现一行三块透明区域 -->
            <el-row class="transparent-button-row">
              <el-col :span="6">
              </el-col>
              <el-col :span="4">
                <button class="transparent-area" @click.stop="handleClick('位置1', props.data.leftInfo)"
                  :class="getButtonClass()"></button>
              </el-col>
              <el-col :span="4">
                <button class="transparent-area" @click.stop="handleClick('位置3', props.data.midRightInfo)"></button>
              </el-col>
              <el-col :span="4">
                <button class="transparent-area" @click.stop="handleClick('位置4', props.data.rightInfo)"
                  :class="getButtonClass()"></button>
              </el-col>
              <el-col :span="6">
              </el-col>
            </el-row>
          </div>
        </div>
      </template>
    </el-popover>
  </div>
</template>




<style scoped>
@keyframes spin {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

.device-text {
  font-size: 25px;
  /* 文字也加大 */
  color: #00ffe0;
  text-align: center;
  margin-top: 4px;
}


/* 定义点的大小 */
.process-node {
  width: 400px;
  /*点固定的大小 */
  height: 150px;
  padding: 0;
  border-radius: 0px;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  text-align: center;
  font-size: 50px;
  /*点里面的图标大小*/
}

.process-node .vue-flow__handle {
  width: unset;
  height: unset;
  font-size: 20px;
  background: transparent;
  border: none;
}

.spinner {
  width: 20px;
  height: 20px;
  border: 1px solid #f3f3f3;
  border-top: 1px solid #2563eb;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

.popconfirm-content {
  font-size: 14px;
  line-height: 1.6;
  padding: 5px;
}

.device-icon {
  width: 420px;
  height: 200px;
  /* 图标放大 */
}

.device-overlay-wrapper {
  position: relative;
  width: 300px;
  height: 200px;
}

.device-icon {
  font-size: 40px;
}

/* 按钮行覆盖在图片上 */
.transparent-button-row {
  position: absolute;
  top: 15%;
  /* ✅ 往下移一点 */
  left: 20%;
  width: 100%;
  height: 100%;
  margin: 0;
  z-index: 2;
}

/* 每个按钮区域透明 */
.transparent-area {
  height: 70%;
  width: 50%;
  background-color: transparent;
  cursor: pointer;
  /* ✅ 圆角边框效果 */
  border: 1px solid rgba(255, 255, 255, 0.3);
  border-radius: 8px;

  transition: border-color 0.2s, background-color 0.2s;
}

/* 可选：hover 高亮区域（开发调试可开） */
.transparent-area:hover {
  background-color: rgba(64, 158, 255, 0.15);
}

/* 有数据：绿色按钮 */
.btn-green {
  background-color: #4caf50;
  border-color: #4caf50;
}

/* 无数据：红色按钮 */
.btn-red {
  background-color: transparent;
  border-color: transparent;
}
</style>
